<template>
  <div class="tea-container">
    <!-- 头部操作区域 -->
    <el-card class="header-card">
      <div class="header-operation">
        <el-button type="primary" @click="handleAdd" style="width: 120px">
          <el-icon><Plus /></el-icon> 添加茶饮
        </el-button>
        <el-select
          v-model="statusFilter"
          placeholder="状态"
          @change="handleFilter"
          style="width: 80px; margin-left: 10px"
        >
          <el-option label="全部" value="" />
          <el-option label="上架" value="1" />
          <el-option label="下架" value="0" />
        </el-select>
        <el-select
          v-model="typeFilter"
          placeholder="类型"
          @change="handleFilter"
          style="width: 80px; margin-left: 10px"
        >
          <el-option label="全部" value="" />
          <el-option label="冷饮" value="冷饮" />
          <el-option label="热饮" value="热饮" />
          <el-option label="冰淇淋" value="冰淇淋" />
        </el-select>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索茶饮名称"
          @keyup.enter="handleFilter"
          clearable
          style="width: 240px; margin-left: 10px"
        >
          <template #suffix>
            <el-icon class="el-input__icon" @click="handleFilter">
              <Search />
            </el-icon>
          </template>
        </el-input>
      </div>
    </el-card>

    <!-- 茶饮列表 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <!-- 表格列保持不变 -->
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="name" label="名称" min-width="150" />
        <!-- 价格列 -->
<el-table-column prop="rmb" label="价格" width="100" align="right">
  <template #default="scope">
    {{ scope.row.rmb }} 元
  </template>
</el-table-column>
        <el-table-column prop="type" label="类型" width="100" />
        <el-table-column prop="beizhu" label="备注" min-width="150" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button type="primary" icon="Edit" size="mini" @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-popconfirm title="确定删除该茶饮吗？" @confirm="handleDelete(scope.row.id)">
                <template #reference>
                  <el-button type="danger" icon="Delete" size="mini">
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px; text-align: right"
      />
    </el-card>

    <!-- 添加/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" title="茶饮信息" width="500px" @close="handleDialogClose">
      <el-form ref="teaForm" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="价格" prop="rmb">
          <el-input v-model="formData.rmb" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="formData.type" style="width: 120px">
            <el-option label="冷饮" value="冷饮" />
            <el-option label="热饮" value="热饮" />
            <el-option label="冰淇淋" value="冰淇淋" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="beizhu">
          <el-input v-model="formData.beizhu" type="textarea" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" style="width: 120px">
            <el-option label="上架" value="1" />
            <el-option label="下架" value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { Plus, Search, Edit, Delete } from '@element-plus/icons-vue'

// 状态管理
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const statusFilter = ref('') // 状态筛选
const typeFilter = ref('')   // 类型筛选
const searchKeyword = ref('') // 名称搜索

// 弹窗相关
const dialogVisible = ref(false)
const formData = reactive({
  id: null,
  name: '',
  rmb: '',
  beizhu: '',
  type: '',
  status: 1
})
const formRules = reactive({
  name: [{ required: true, message: '请输入茶饮名称', trigger: 'blur' }],
  rmb: [{ required: true, message: '请输入茶饮价格', trigger: 'blur' }]
})

// 生命周期
onMounted(() => {
  fetchTableData()
})

// 获取列表数据（修改为条件查询）
const fetchTableData = async () => {
  try {
    let response = null
    
    // 根据筛选条件选择不同的接口
    if (searchKeyword.value) {
      // 按名称搜索
      response = await axios.get('/api/tea/search/name', {
        params: { name: searchKeyword.value }
      })
    } else if (statusFilter.value !== '') {
      // 按状态筛选
      response = await axios.get('/api/tea/search/status', {
        params: { status: statusFilter.value }
      })
    } else if (typeFilter.value !== '') {
      // 按类型筛选
      response = await axios.get('/api/tea/search/type', {
        params: { type: typeFilter.value }
      })
    } else {
      // 无筛选条件，获取全部数据
      response = await axios.get('/api/tea/getAll')
    }
    
    tableData.value = response.data.data || []
    // 由于后端接口未返回分页信息，此处假设total为查询结果总数
    total.value = tableData.value.length
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  }
}

// 筛选处理
const handleFilter = () => {
  currentPage.value = 1
  fetchTableData()
}

// 分页处理（由于后端接口未支持分页，此处仅重置页码）
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchTableData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchTableData()
}

// 新增
const handleAdd = () => {
  formData.id = null
  formData.name = ''
  formData.rmb = ''
  formData.beizhu = ''
  formData.type = ''
  formData.status = 1
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  formData.id = row.id
  formData.name = row.name
  formData.rmb = row.rmb
  formData.beizhu = row.beizhu
  formData.type = row.type
  formData.status = row.status
  dialogVisible.value = true
}

// 保存
const handleSave = async () => {
  try {
    if (formData.id) {
      await axios.post('/tea/updateById', formData)
    } else {
      await axios.post('/tea/add', formData)
    }
    dialogVisible.value = false
    fetchTableData()
    ElMessage.success('操作成功！')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('操作失败，请重试！')
  }
}

// 关闭弹窗
const handleDialogClose = () => {
  formData.id = null
  formData.name = ''
  formData.rmb = ''
  formData.beizhu = ''
  formData.type = ''
  formData.status = 1
}

// 删除
const handleDelete = async (id) => {
  try {
    await axios.delete('/tea/deleteById', { params: { id } })
    fetchTableData()
    ElMessage.success('删除成功！')
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败，请重试！')
  }
}
</script>

<style scoped>
.tea-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.header-operation {
  display: flex;
  align-items: center;
}

.table-card {
  padding: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 5px;
}
</style>